var selectedUserId = null;
var MAVRO_ACCOUNT_TYPE_INFO = 1;
var MAVRO_BONUS_TYPE_INFO = 2;
var MAVRO_NOACTIVE_TYPE = 'noactive';
var MAVRO_NOACTIVE_TYPE_ACTIVE = 'noactive_active';
var MAVRO_ACTIVE_TYPE = 'active';
var MAVRO_SELLED_TYPE = 'selled';
var MAVRO_LEADER_BONUS_TYPE = 'leader_bonus';
var ACCRULE_TO_CONVERT = 13;
var showAccountColumns;
var showBonusColumns;
var showInactiveAccounts = false;
var defrostedCell = [];
var id_structure=950;
DFCell = function(index, sec) {
    this.init(index, sec);
};
DFCell.prototype = {
    index: 0,
    sec: 0,
    min: 0,
    hours: 0,
    init: function(index, sec) {
        this.index = index;
        this.sec = sec;
        this.min = Math.floor(this.sec / 60);
        this.hours = Math.floor(this.sec / 3600);
        var _this = this;
        setTimeout(function() {
            _this.show.call(_this);
        },
        100);
    },
    startCounter: function() {
        this.sec = this.sec - 1;
        this.min = Math.floor(this.sec / 60);
        this.hours = Math.floor(this.sec / 3600);
        var _this = this;
        if (this.sec > -1) {
            setTimeout(function() {
                _this.show.call(_this);
            },
            1000);
        }
    },
    show: function() {
        var label = getTranslation('cool_defrosted');
        if (this.hours > 0) {
            label = this.hours + ' ' + getTranslation('hourses');
        } else if (this.min > 0) {
            label = this.min + ' ' + getTranslation('minutes');
        } else if (this.sec > 0) {
            label = this.sec + ' ' + getTranslation('seconds');
        }
        $('tr[datagrid-row-index="' + this.index + '"] td[field="fr"] div', $('#mavro').parent()).html(label);
        this.startCounter();
    }
};
function myStrToTime(str) {
    var pices = str.split(' ');
    var date_pices = pices[0].split('-').map(function(item) {
        return parseInt(item, 10);
    });
    var time_pices = pices[1].split(':').map(function(item) {
        return parseInt(item, 10);
    });
    return new Date(date_pices[0], date_pices[1] - 1, date_pices[2], time_pices[0], time_pices[1], time_pices[2]);
}
function setDefaultShowAccountColumns() {
    showAccountColumns = {
        'opertype_description': false,
        'name': false,
        'description': false,
        'operation_type': false,
        'crtime': false,
        'amount': false,
        'fio': false,
        'email': false
    };
}
function setDefaultShowBonusColumns() {
    showBonusColumns = {
        'crdate': false,
        'fio': false,
        'percent': false,
        'amount': false,
        'descr': false
    };
}
function createDG() {
    var rows= []; 
    $.ajax({
			url:"/Home/user/getMafuluoLog",
			type: 'get',
		    dataType: 'json',
			success:function(result){
				alert(1);
				rows=result.mavro;
				$('#mavro').datagrid({
			        fitColumns: true,
			        fit: true,
			        singleSelect: true,
			        columns: [[{
			            field: 'code_number',
			            title: getTranslation('ID'),
			            width: 100,
			            formatter: function(value) {
			            	  return value;
			            }
			        },
			        {
			            field: 'status',
			            title: getTranslation('Type'),
			            width: 100,
			            formatter: function(value) {
			                switch (value) {
			                case 'MAVRO_NOACTIVE_TYPE':
			                    return getTranslation('macc_type_in');
			                case 'MAVRO_NOACTIVE_TYPE_ACTIVE':
			                    return getTranslation('macc_type_real');
			                case 'MAVRO_SELLED_TYPE':
			                    return getTranslation('macc_type_out');
			                case 'MAVRO_ACTIVE_TYPE':
			                    return getTranslation('macc_type_real');
			                case 'MAVRO_LEADER_BONUS_TYPE':
			                    return getTranslation('macc_type_leader_bonus');
			                }
			                return '';
			            }
			        },
			        {
			            field: 'create_date',
			            title: getTranslation('Creation date'),
			            width: 100
			        },
			        {
			            field: 'fr',
			            title: getTranslation('Unfrozen date'),
			            width: 100,
			            align: 'center',
			            formatter: function(value, row, index) {;
			                var ret = '';
			                if (row.freezed == 1) {
			                    ret = value;
			                }
			                if (parseInt(row.df_sec, 10)) {
			                    ret = '';
			                    defrostedCell.push(new DFCell(index, row.df_sec));
			                }
			                return getTranslation(ret);
			            }
			        },
			        {
			            field: 'mvr',
			            title: getTranslation('Purse'),
			            width: 100,
			            formatter: function(value, rowData) {
			                if (typeof(value) != 'undefined') {
			                    var f = '';
			                    var arr = value.split(":");
			                    switch (rowData.type_info) {
			                    case 'MAVRO_ACCOUNT_TYPE_INFO':
			                      //  f = 'mavroShowAccountInfo(' + rowData.id_object + ')';
			                    	return getTranslation(arr[0]) + (arr[1] ? " " + arr[1] : '');
			                        break;
			                    case 'MAVRO_BONUS_TYPE_INFO':
			                        f = "mavroShowBonusInfo('" + rowData.id + "')";
			                        return '<a href="#" onclick="' + f + ';">' + getTranslation(arr[0]) + (arr[1] ? " " + arr[1] : '') + '</a>';
			                        break;
			                    }   
			                }
			                return '';
			            }
			        },
			        {
			            field: 'mtd',
			            title: getTranslation('Mavro_money_today'),
			            width: 116,
			            align: 'right',
			            formatter: function(value, row) {
			                var color = "green";
			                switch (true) {	
			                case (row.status == 'MAVRO_SELLED_TYPE') : var color = "green";
		                    break;
			                case(row.mavro_type == 'MAVRO_NOACTIVE_TYPE' || row.mavro_type == 'MAVRO_NOACTIVE_TYPE_ACTIVE') : var color = "red";
			                    break;
			                case (row.freezed == 1) : var color = "blue";
			                    break;
			                case (row.mavro_type =='MAVRO_LEADER_BONUS_TYPE') : var color = "blue";
			                    break; 
			                }
			                if (row.id_pause > 0 && row.id_pause != 4) {
			                    var color = "blue";
			                    if (row.id_pause == 4) {
			                        var color = "#FF9800";
			                    }
			                }
			                var arr = value.split(":");
			                return '<span style="color:' + color + '; font-weight:bold;">' + arr[0] + '</span>' + (arr[1] ? " " + arr[1] : '');
			            }
			        },
			        {
			            field: 'descr',
			            title: getTranslation('common_description'),
			            width: 100,
			            align: 'left',
			            formatter: function(value, row) {
			                if (row.id_pause == 4) {
			                    return '<span style="color:' + '#FF9800' + '; font-weight:bold;"><i>' + getTranslation('intermediate_mavro') + '</i></span>';
			                }
			                return getTranslation(value);
			            }
			        }
			        ]],
			        rowStyler: function(rowIndex, rowData) {
			            var color = "";
			            var background_color = "";
			            if (rowData.freezed == 1) {
			                background_color = "background-color:#dff8ff;";
			            }
			            switch (rowData.mavro_type) {
			            case MAVRO_NOACTIVE_TYPE:
			            case MAVRO_NOACTIVE_TYPE_ACTIVE:
			                color = "color:#888888;";
			                break;
			            case MAVRO_SELLED_TYPE:
			                color = "color:#888888;";
			                break;
			            case MAVRO_LEADER_BONUS_TYPE:
			                background_color = "background-color:#dddddd;";
			                color = "color:#444444;";
			                break;
			            }
			            if (rowData.color) {
			                background_color = "background-color:" + rowData.color + ";";
			            }
			            return background_color + ' ' + color + rowData.html_style;
			        },
			        toolbar: toolbar
			    }).datagrid("loadData", {rows: rows});
				
			}
	 })
    $('.icon-wand').attr('title', getTranslation('convert_hint'));
    $(".datagrid-toolbar").append('<div style="padding:5px 10px; float:right">' + getTranslation('message_about_charging_of_mavro') + '</div>');
}
function mavroShowAccountInfo(id_account) {
    var $info = $('<div class="mavro_info"></div>');
    $info.appendTo('body');
    $info.append('<div class="mavro_info_datagrid"></div>');
    mavroDrawAccountInfo(id_account, $info);
}
function mavroShowBonusInfo(id_currency_mavro, id_currency) {
    var $info = $('<div class="mavro_info"></div>');
    $info.appendTo('body');
    $info.append('<div class="mavro_info_datagrid"></div>');
    mavroDrawBonusInfo(id_currency_mavro, id_currency, $info);
}
function mavroDrawBonusInfo(id_currency_mavro, id_currency, $info) {
    $info.dialog({
        width: 1000,
        height: 500,
        collapsible: true,
        minimizable: false,
        maximizable: false,
        modal: true,
        title: getTranslation('common_operations'),
        buttons: [{
            text: getTranslation('Close'),
            iconCls: 'icon-cancel',
            handler: function() {
                mavroInfoOnClose($info);
            }
        }],
        onBeforeOpen: function() {
            setDefaultShowBonusColumns();
            $('.mavro_info_datagrid', $info).datagrid({
                url: baselocation+"/mavro/bonusDetail",
                queryParams: {
                //    'a': 'ib',
                    'i': id_currency_mavro
                //    'id_currency': id_currency,
                 //   'u': (selectedUserId ? selectedUserId: 0)
                },
                pageSize: 25,
                pageList: ['10', '25', '50', '100'],
                fitColumns: true,
                fit: true,
                singleSelect: true,
                pagination: true,
                columns: [[
				 {
                    field: 'Part',
                    title: getTranslation('Member'),
                    width: 100,
                    formatter: function(value, row) {
                        showBonusColumns['Part'] = true;
                        return value;
                    }
                },
                {
                    field: 'crdate',
                    title: getTranslation('Creation date'),
                    width: 100,
                    formatter: function(value, row) {
                        showBonusColumns['crdate'] = true;
                        return value;
                    }
                },
                {
                    field: 'a',
                    title: getTranslation('mavro'),
                    width: 100,
                    formatter: function(value, row) {
                        showBonusColumns['a'] = true;
                        return value+' Mavro-USD';
                    }
                },
                {
                    field: 'percent',
                    title: getTranslation('common_percent'),
                    width: 100,
                    formatter: function(value, row) {
                        showBonusColumns['percent'] = true;
                        return value + ' %'
                    }
                },
                {
                    field: 'descr',
                    title: getTranslation('common_description'),
                    width: 100,
                    formatter: function(value, row) {
                        if (value != null && value != '') {
                            showBonusColumns['descr'] = true;
                            return value;
                        }
                    }
                }]],
                rowStyler: function(rowIndex, rowData) {
                    var color = "";
                    var background_color = "";
                    if (rowData.status == 2) {
                        color = "color:#888888;";
                    }
                    date = new Date();
                    var month = date.getMonth() + 1;
                    newdate = date.getDate() + '.' + (month < 10 ? '0': '') + month + '.' + date.getFullYear();
                    if (rowData.ufdate > newdate) background_color = "background-color:#dff8ff;";
                    if (rowData.user_status == 2) background_color = "background-color:pink;";
                    return background_color + ' ' + color;
                },
                onLoadSuccess: function(data) {
                    var columns = $(this).datagrid('getColumnFields');
                    var _this = this;
                    $.each(columns,
                    function(i, obj) {
                        if (showBonusColumns[obj]) {
                            $(_this).datagrid('showColumn', obj);
                        } else {
                            $(_this).datagrid('hideColumn', obj);
                        }
                    });
                    $(_this).datagrid('fitColumns');
                }
            });
        },
        onClose: function() {
            mavroInfoOnClose($info);
        }
    });
}
function mavroInfoOnClose($info) {
    $info.dialog('destroy');
}
function editComment(id, comment, date) {
		$.ajax({
			url:baselocation+"/mavro/getMyFuture/",
			type: 'get',
			data :{id:id},
			dataType: 'json',
			success:function(result){
				if(result.my_future!=""&&result.my_future!=null){
					comment=result.my_future;
				}
			    $win = $('<div><textarea style="width: 98%; height: 200px;">' + (comment ? comment: getTranslation('my_dreams_default')) + '</textarea>' + '<div style="margin-top: 20px; text-align: center;"><a class="save" iconCls="icon-ok">' + getTranslation('Save') + '</a>&nbsp;&nbsp;<a class="cancel" iconCls="icon-cancel">' + getTranslation('Cancel') + '</a></div></div>');
			    $win.appendTo('body');
			    $win.window({
			        title: 'A' + id,
			        modal: true,
			        height: 330,
			        width: 500,
			        onClose: function() {
			            $(this).window('destroy');
			        }
			    });
			    $('a.save', $win).linkbutton().click(function() {
			        $.ajax({
			            url: baselocation+"/mavro/getMyFuture/",
			            type: 'post',
			            data: {
			                a: 'set_user_comment',
			                id: id,
			                a_crtime: date,
			                comment: $('textarea', $win).val()
			            },
			            success: function(data) {
			                if (data.code==1) {
			                    $('#mavro').datagrid('reload');
			                    $win.window('close');
			                } else {
			                    showError(data[23]);
			                }
			            }
			        });
			    });
			    $('a.cancel', $win).linkbutton().click(function() {
			        $win.window('close');
			    });
			    $win.window('open')
		}
	});
;
}
$(function() {
    selectedUserId = user_perms.id;
	is_dec=true;
    createDG();
    $('#getMavro').click(function() {
        createWant();
        return false;
    });
});